<?php

namespace app\system\controller\business;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use hehe\Str;
use hehe\Trade;
use think\facade\Db;
use think\facade\Lang;


class Business extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['name_cn', 'name_ko', 'describe', 'customer.corp_name_ko', 'no'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\business\Business;
    }


    /**
     * 设置状态
     */
    public function setStatus(){
        $param = $this->request->param();
        $res = db::name('business')->where(['no' => $param['no']])->find();
//        print_r($res);
        $status = $res['status'] !== null && $res['status'] !== ''  ? explode(',', $res['status']) : [];
//        print_r($status);
        if(in_array($param['status'], $status)) {
            $param_status = $param['status'];
            $new_status = array_filter($status, function($item) use ($param_status) {
                return ($item != $param_status);
            });
            $status = $new_status;
        }else{
            $status[] = $param['status'];
        }
//        print_r($status);die;
        $status = empty($status) ? null : implode(',', $status);
        $update = [
            'status' => $status,
            'update_time' => $this->timestamp
        ];
        $result = db::name('business')->where(['no' => $param['no']])->update($update);
        if($result){
            $this->success('', [
                'status' => $status == null ? [] : explode(',', $status),
                'sum_status' => $this->sumStatus()
            ]);
        }else{
            $this->error();
        }
    }

    public function sumStatus(): array{
        $sql = <<<sql
SELECT
  GROUP_CONCAT(no) AS combined_no,
  GROUP_CONCAT(status) AS combined_status,
  SUM(CASE WHEN status IS NULL THEN 1 ELSE 0 END) AS count_1,
  SUM(CASE WHEN FIND_IN_SET('1', status) AND user_id > 0 THEN 1 ELSE 0 END) AS count_2,
  SUM(CASE WHEN FIND_IN_SET('0', status) THEN 1 ELSE 0 END) AS count_3,
  SUM(CASE WHEN FIND_IN_SET('1', status) AND user_id = 0 THEN 1 ELSE 0 END) AS count_4
FROM (
  SELECT no, MAX(status) AS status, MAX(user_id) AS user_id
  FROM ba_business where filter_id={$this->filter['id']}
  GROUP BY no
) AS subquery;

sql;
        $result = db::query($sql);
//        print_r($result);die;
        return $result[0];

    }


    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {

        $lang = Lang::getLangSet();
        $lang = $lang == 'ko' ? 'ko' : 'cn';
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $keyword = $this->request->param('quickSearch');
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->with(['admin', 'quotation' => function($query){
                $query->where(['filter_id' => $this->filter['id']]);
            }])
            ->withJoin(['customer'], $this->withJoinType)
            ->alias($alias)
            ->where($where)->where(['business.filter_id' => $this->filter['id']]);
        $param = $this->request->param();
        $param['status'] = empty($param['status']) ? '0' : $param['status'];

        if($keyword){
//            $res = $res->whereOr('customer.corp_name_ko', 'like', '%' . $keyword . '%');
//            $res = $res->whereHas('customer', function($query) use ($keyword){
//                $query->where('like', 'corp_name_ko', '%' . $keyword . '%');
//            });
        }

        if(empty($param['status'])){ // 全部
            $res = $res->where("(status NOT LIKE '0,%' OR status IS NULL) AND (status NOT LIKE '%,0,%' OR status IS NULL) AND (status NOT LIKE '%,0' OR status IS NULL) AND (status != '0' OR status IS NULL)");
        }

        if($param['status'] == 1){ // 进行中
            $res = $res->where("status IS NULL");
        }
        if($param['status'] == 2){ // 已成交
            $res = $res->where('user_id', '>', 0)->where('FIND_IN_SET(:value,status)',['value' => '1']);
        }
        if($param['status'] == 3){ // 已终止
            $res = $res->where('FIND_IN_SET(:value,status)',['value' => '0']);
        }
        if($param['status'] == 4){ // 内部(完成)
            $res = $res->where(['user_id' => 0])->where('FIND_IN_SET(:value,status)',['value' => '1']);
        }

        if(!empty($param['no'])){
            $res = $res->where(['business.no' => $param['no']]);

        }

        if(isset($param['customer_id'])){
            $res = $res->where(['user_id' => $param['customer_id']]);
        }

        $res = $res->order($order)->paginate($limit);

        $list = $res->items();
        foreach($list as $key => $val){
            $list[$key]['files'] = empty($val['files']) ? [] : json_decode($val['files'], true);
            if(empty($val['name_' . $lang])){
                if($lang == 'ko') $list[$key]['name'] = html_entity_decode($val['name_cn']);
                if($lang == 'cn') $list[$key]['name'] = html_entity_decode($val['name_ko']);
            } else {
                $list[$key]['name'] = html_entity_decode($val['name_' . $lang]);
            }
            $list[$key]['describe'] = empty($val['describe']) ? '' : html_entity_decode($val['describe']);
            $list[$key]['name_cn'] = empty($val['name_cn']) ? '' : html_entity_decode($val['name_cn']);
            $list[$key]['name_ko'] = empty($val['name_ko']) ? '' : html_entity_decode($val['name_ko']);
        }

        $sum_status = $this->sumStatus();


        $this->success('', [
            'list' => $list,
            'total' => $res->total(),
            'remark' => get_route_remark(),
            'sum_status' => $sum_status
        ]);
    }

    public function add(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            if(!empty($data['images'])) $data['images'] = implode(',', $data['images']);
//            print_r($data);die;
            if(!empty($data['files'])) {

                $attachment = db::name('attachment')->whereIn('url', $data['files'])->select();
                $files = [];
                foreach($attachment as $val){
                    $files[] = [
                        'id' => $val['id'],
                        'url' => $val['url'],
                        'name' => $val['name']
                    ];
                }
                $data['files'] = json_encode($files);
            }

            $data['admin_id'] = $this->auth->id;
            $data['out_trade_no'] = Trade::generateTradeNo();
            $data['filter_id'] = $this->filter['id'];

            $business = Db::name('business')->where(['filter_id' => $this->filter['id']])->order('no desc')->find();
            if($business){
                $data['no'] = $business['no'] + 1;
            }else{
                $data['no'] = 1;
            }

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $data['create_time'] = $this->timestamp;
                $result = db::name('business')->insert($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    /**
     * 添加进程
     */
    public function addProcess(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $pid = $data['id'];
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            if(!empty($data['images'])) $data['images'] = implode(',', $data['images']);
            if(!empty($data['files'])) {
                $attachment = db::name('attachment')->whereIn('url', $data['files'])->select();
                $files = [];
                foreach($attachment as $val){
                    $files[] = [
                        'id' => $val['id'],
                        'url' => $val['url'],
                        'name' => $val['name']
                    ];
                }
                $data['files'] = json_encode($files);
            }

            $p_data = db::name('business')->where(['id' => $pid])->find();

            $data['admin_id'] = $this->auth->id;
            $data['user_id'] = $p_data['user_id'];
            $data['status'] = $p_data['status'];
            $data['out_trade_no'] = $p_data['out_trade_no'];
            $data['no'] = $p_data['no'];

            if(isset($data['create_date_text'])) unset($data['create_date_text']);
            if(isset($data['create_time_text'])) unset($data['create_time_text']);
            $data['filter_id'] = $this->filter['id'];

            $result = false;
            $this->model->startTrans();
            try {
                $result = db::name('business')->insert($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }



    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $row['name_ko'] = empty($row['name_ko']) ? '' : html_entity_decode($row['name_ko']);
        $row['name_cn'] = empty($row['name_cn']) ? '' : html_entity_decode($row['name_cn']);
        $row['describe'] = empty($row['describe']) ? '' : html_entity_decode($row['describe']);

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

//            print_r($data);die;

            $data   = $this->excludeFields($data);
            $data['images'] = empty($data['images']) ? null : implode(',', $data['images']);
            $data['files'] = empty($data['files']) ? [] : $data['files'];
            $data['files'] = is_array($data['files']) ? $data['files'] : explode(',', $data['files']);
            $old_files = [];
            $new_files = [];
            $row['files'] = empty($row['files']) ? [] : json_decode($row['files'], true);
            foreach($data['files'] as $val){
                if(strstr($val, '/storage/default/')){
                    $new_files[] = $val;
                }else{
                    $old_files[] = $val;
                }
            }
            $files = [];
            foreach($row['files'] as $val){
                foreach($old_files as $v){
                    if($val['name'] == $v){
                        $files[] = $val;
                    }
                }
            }
            if($new_files){
                $attachment = db::name('attachment')->whereIn('url', $new_files)->select();
                foreach($attachment as $val){
                    $files[] = [
                        'id' => $val['id'],
                        'url' => $val['url'],
                        'name' => $val['name']
                    ];
                }
            }
            $data['files'] = json_encode($files);
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                if($row['id'] == $row['no']){
                    $children_update = [
                        'user_id' => $data['user_id']
                    ];
                    if(!empty($data['name_cn'])) $children_update['name_cn'] = trim($data['name_cn']);
                    if(!empty($data['name_ko'])) $children_update['name_ko'] = trim($data['name_ko']);
                    db::name('business')->where(['no' => $row['no']])->update($children_update);
                }

                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
        $row = $row->toArray();
        if(!empty($row['files'])){
            $row['files'] =  json_decode($row['files'], true);
            $files = [];
            foreach($row['files'] as $val){
                $files[] = $val['name'];
            }
            $row['files'] = $files;
        }

        $this->success('', [
            'row' => $row
        ]);
    }

    public function setInfo(): void {
        $data = $this->request->post();
        $data['product_images'] = empty($data['product_images']) ? null : implode(',', $data['product_images']);
        $data['product_files_text'] = empty($data['product_files_text']) ? [] : $data['product_files_text'];
        $data['product_files'] = is_array($data['product_files_text']) ? $data['product_files_text'] : explode(',', $data['product_files_text']);
        $old_files = [];
        $new_files = [];
        $row = db::name('business')->where(['no' => $data['no']])->find();
        $row['product_files'] = empty($row['product_files']) ? [] : json_decode($row['product_files'], true);
        foreach($data['product_files'] as $val){
            if(strstr($val, '/storage/default/')){
                $new_files[] = $val;
            }else{
                $old_files[] = $val;
            }
        }
        $files = [];
        foreach($row['product_files'] as $val){
            foreach($old_files as $v){
                if($val['name'] == $v){
                    $files[] = $val;
                }
            }
        }
        if($new_files){
            $attachment = db::name('attachment')->whereIn('url', $new_files)->select();
            foreach($attachment as $val){
                $files[] = [
                    'id' => $val['id'],
                    'url' => $val['url'],
                    'name' => $val['name']
                ];
            }
        }
        $data['product_files'] = json_encode($files);
        $result = false;
        $this->model->startTrans();
        try {
            $data['update_time'] = $this->timestamp;
            unset($data['product_files_text']);
            $result = db::name('business')->where(['no' => $data['no']])->update($data);
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
        if ($result !== false) {
            $business = db::name('business')->where(['no' => $data['no']])->find();
            $product_files = empty($business['product_files']) ? [] : json_decode($business['product_files'], true);
            $product_files_text = [];
            foreach($product_files as $key => $val){
                $product_files_text[$key] = $val['url'];
            }
            $this->success(__('Update successful'), [
                'product_files' => $product_files,
                'product_files_text' => $product_files_text
            ]);
        } else {
            $this->error(__('No rows updated'));
        }

    }

    /**
     * 删除报价单
     */
    public function delQuotationFile(): void {
        $id = $this->request->param('id');
        $update = [
            'quotation_file' => null,
            'update_time' => $this->timestamp
        ];
        db::name('business_quotation')->where(['id' => $id])->update($update);
        $this->success();
    }

    /**
     * 上传报价单
     */
    public function setQuotationFile(): void{
        $param = $this->request->post();
//        print_r($param);
        $quotation_file = json_encode($param['quotation_file']);
        $update = [
            'quotation_file' => $quotation_file,
            'update_time' => $this->timestamp
        ];
        db::name('business_quotation')->where(['id' => $param['id']])->update($update);
        $this->success();
    }


    /**
     * 删除备注
     */
    public function delNote(){
        $param = $this->request->param();
        db::name('business_quotation_note')->where(['id' => $param['id']])->delete();
        $this->success();
    }

    /**
     * 添加备注
     */
    public function addNote(){
        $param = $this->request->param();
        $param['admin_id'] = $this->auth->id;
        $param['create_time'] = $this->timestamp;
        $note_id = db::name('business_quotation_note')->insertGetId($param);
        if($note_id){
            $this->success('', [
                'id' => $note_id,
                'content' => $param['content'],
                'admin' => [
                    'username' => $this->auth->username
                ]

            ]);
        }else{
            $this->error();
        }
    }

    /**
     * 隐藏报价
     */
    public function hideQuotation(){
        $param = $this->request->param();
        db::name('business_quotation')->where(['id' => $param['id']])->update(['hide' => 1]);
        $this->success();
    }
    /**
     * 显示报价
     */
    public function showQuotation(){
        $param = $this->request->param();
        db::name('business_quotation')->where(['id' => $param['id']])->update(['hide' => 0]);
        $this->success();
    }


































}